package dao.impl;

import dao.UserDao;
import po.User;
import util.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public User login(User user) {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        try{
            //获取数据库连接
            con= BaseDao.getConnection();
            String sql="select * from user where username=? and password=?";
            //预处理
            ps=con.prepareStatement(sql);
            ps.setObject(1,user.getUsername());
            ps.setObject(2,user.getPassword());
            rs=ps.executeQuery();
            User us=new User();
            if (rs.next()){
                //从结果集取值
                us.setUsername(rs.getString("username"));
                us.setPassword(rs.getString("password"));
                return us;
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(con,ps,rs);
        }

        return null;
    }

    @Override
    public boolean register(User user) {
        String sql="insert into user(username,password) values(?,?)";
        List<Object> list= new ArrayList<>();
        list.add(user.getUsername());
        System.out.println(user.getUsername());

        list.add(user.getPassword());
        System.out.println("a1");
        return BaseDao.addUpdateDelete(sql,list.toArray());
    }

    @Override
    public List<User> selectUser(String sql, Object[] arr) {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con=BaseDao.getConnection();
            ps=con.prepareStatement(sql);
            if (arr!=null){
                for (int i=0;i<arr.length;i++){
                    ps.setObject(i+1,arr[i]);
                }
            }

            rs=ps.executeQuery();
            List<User> list=new ArrayList<>();
            while(rs.next()){
                User user=new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                list.add(user);
            }
            return list;
        }catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(con,ps,rs);
        }
        return null;
    }

}
